import { CanActivate, ExecutionContext, HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';

import { UserRoleService } from 'src/modules/user-role/user-role.service';
import JWT from 'src/utils/jwt';

@Injectable()
export class RolesGuard implements CanActivate {
  constructor(
    private readonly userRoleService: UserRoleService,
    private readonly reflector: Reflector
  ) {}
  async canActivate(
    context: ExecutionContext
  ): Promise<boolean> {
    const roles = this.reflector.get('roles', context.getHandler());
    if (!roles) {
      return true;
    }
    const request = context.switchToHttp().getRequest();
    const token = request.headers.authorization
    const payload = JWT.verify(token);
    if (!payload) {
      throw new HttpException('登录超时,请重新登录', HttpStatus.UNAUTHORIZED);
    }
    try {
      const result = await this.userRoleService.findUserOfRole(payload.id)
      return matchRoles(roles, result[0].role_key);
    } catch (error) {
      // 如果当前用户没有角色信息或其他异常则不通过验证
      throw new HttpException('没有访问权限，请联系管理员', HttpStatus.FORBIDDEN);
    }
  }
}
/**
 * 角色鉴权
 * @param roles 接口所需角色
 * @param current 当前登录用户角色
 * @returns 
 */
function matchRoles(roles, current) {
  if(roles.includes(current)) {
    return true
  } else {
    throw new HttpException('没有访问权限，请联系管理员', HttpStatus.FORBIDDEN);
  }
}
